<?php

namespace app\parent\controller\v1;

use app\common\controller\ParentController;
use app\models\ParentInformationModel;
use think\Cache;
use think\Config;

class Register extends ParentController
{
    /**
     * 登陆接口
     * User: wufeng
     * Date: 2019/5/10.
     */
    public function login()
    {
        $param = input('post.');
        $rule = [
            'username' => 'require|number',
            'password' => 'require|length:6,16',
        ];
        $message = [
            'username.require' => '用户名不能为空',
            'username.number' => '用户名只能数字',
            'password.require' => '密码不能为空',
            'password.length' => '密码长度不正确',
        ];
        $result = $this->validate($param, $rule, $message);
        if (true !== $result) {
            $this->fail('PARAM_ERROR');
        }

        $parentInformationModel = new ParentInformationModel();
        $parentInformation = $parentInformationModel->get(['username' => $param['username']]);
        if (null === $parentInformation) {
            $this->fail('USERNAME_NOT_EXIST');
        }
        $this->cachePrefix = 'PARENT_TOKEN:'.$this->token;
        $encodePassword = self::encodePassword($param['password'], $parentInformation['salt']);
        if ($parentInformation['password'] !== $encodePassword) {
            $cacheKey = $this->cachePrefix.'login_error_times_'.$param['username'];
            if (Cache::has($cacheKey)) {
                if (Cache::get($cacheKey) >= Config::get('max_login_error_times')) {
                    $this->fail('EXCEED_MAX_ERROR_LOGIN_TIMES');
                }
                Cache::inc($cacheKey);
            } else {
                Cache::set($cacheKey, 1, strtotime(date('Y-m-d').' 23:59:59') - time());
            }
            $this->fail('PASSWORD_NOT_RIGHT');
        }

        if (0 === (int) $parentInformation['status']) {
            $this->fail('USER_RESTRICT_LOGIN');
        }

        //更新最后登录状态
        $parentInformationModel::update([
            'last_login' => $this->request->time(),
            'last_ip' => $this->request->ip(),
        ], ['id' => $parentInformation['id']]);

        // 登入成功 先写基本session cookie
        $sessionData = [
            'user_id' => $parentInformation['id'],
            'name' => $parentInformation['name'],
            'img' => $parentInformation['img'],
            'student_id' => $parentInformation['student_id'],
            'username' => $parentInformation['username'],
        ];

        $expireTime = Config::get('login_validity_time') ?: 86400;
        Cache::set($this->cachePrefix, $sessionData, $expireTime);

        $this->win('登录成功', ['userInfo' => $sessionData, 'token' => $this->token]);
    }

    /**
     * 修改密码
     * User: wufeng
     * Date: 2020/03/08.
     */
    public function changePassword()
    {
        $params = input('post.');
        $parentInformation = (new ParentInformationModel())->get(['id' => parent_get_current_user_id()]);
        $encodePassword = self::encodePassword($params['password'], $parentInformation['salt']);
        if ($parentInformation['password'] !== $encodePassword) {
            $this->fail('PASSWORD_NOT_RIGHT');
        }

        if ($params['password'] === $params['one_password']) {
            $this->fail('PASSWORD_CAN_NOT_ALIKE');
        }
        if ($params['one_password'] !== $params['two_password']) {
            $this->fail('PASSWORD_NOT_ALIKE');
        }
        $data['salt'] = md5(date('Y-m-d H:i:s'));
        $data['password'] = self::encodePassword($params['one_password'], $data['salt']);
        (new ParentInformationModel())->save($data, ['id' => parent_get_current_user_id()]);
        $this->win('修改成功');
    }

    /**
     * 功能:对用户输入的明文密码进行加密(还记不记得csdn的杯具).
     *
     * @param string $password 明文密码
     * @param string $salt     混淆字符串（盐）,防止简单的MD5加密被逆向破解
     *
     * @return string 加密后的密码
     */
    public static function encodePassword($password, $salt)
    {
        $encryptd_password = md5(md5($password).$salt);

        return substr($encryptd_password, 0, 32);
    }

    /**
     * 初始化.
     */
    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        if (!$this->token) {
            $this->token = parent_generate_token();
        }
    }
}
